package cn.egame.extraction.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.egame.common.data.BaseDao;
import cn.egame.common.data.SqlUtils;
import cn.egame.common.exception.ExceptionCommonBase;
import cn.egame.common.util.Utils;
import cn.egame.interfaces.EnumType.AppParameterParamType;
import cn.egame.interfaces.EnumType.AppParameterType;
import cn.egame.interfaces.EnumType.SysParameterType;
import cn.egame.interfaces.pu.AppParameter;

public class ParameterAppServiceDao extends BaseDao {
    private final static String STR_SELECt_PARAMETER_APP_INFO = "id,parent_id,type,name,param,sort,enable,depth,remark,pic_id,begin_time,end_time,update_time,operator_id";

    public ParameterAppServiceDao() throws ExceptionCommonBase {
        super("egame_game");
    }

    public AppParameter getAppParameterById(int id) throws ExceptionCommonBase {
        String sql = "select " + STR_SELECt_PARAMETER_APP_INFO + " FROM t_parameter_app where id = " + id;
        Connection conn =null;
        ResultSet rs =null;
        try {
            conn = this.getConnection();
            rs = this.executeQuery(conn, sql);
            if (rs.next()) {
                return formatAppParameter(rs);
            }
            return null;
        } catch (SQLException e) {
            throw ExceptionCommonBase.throwExceptionCommonBase(e);
        } finally {
            this.close(rs);
            this.releaseConnection(conn);
        }
    }

    public List<Integer> listAppParameterIdsByType(AppParameterType type, int depth) throws ExceptionCommonBase {
        String sql = "select id FROM t_parameter_app where " + " type = " + type.value() + " and depth =" + depth + " and enable =1 order by sort asc";
        return this.getListInteger(sql);
    }
    
    
    public List<Integer> listAppParameterIdsByParam(AppParameterParamType param) throws ExceptionCommonBase {
        String sql = "select id FROM t_parameter_app where " + " param like " + SqlUtils.QuataLikeStr(param.value()) +  " and enable =1 order by sort asc";
        return this.getListInteger(sql);
    }

    public List<Integer> listAppParameterIdsByParentId(int parentId,int appId) throws ExceptionCommonBase {
        String sql = "select id  FROM t_parameter_app where  ( parent_id = " + parentId + " or id = "+appId+" ) and enable =1 order by sort desc";
        return this.getListInteger(sql);
    }

    public List<AppParameter> listAppParameterByIds(List<Integer> ids) throws ExceptionCommonBase {
        List<AppParameter> resultList = new ArrayList<AppParameter>();
        if (ids != null && ids.size() > 0) {

            String sql = "select " + STR_SELECt_PARAMETER_APP_INFO + " FROM t_parameter_app" + " where id in ( " + Utils.toString(ids) + ")  order by sort desc, update_time desc";
            Connection conn =null;
            ResultSet rs = null;
            try {
                 conn = this.getConnection();
                 rs = this.executeQuery(conn, sql);
                while (rs.next()) {
                    resultList.add(formatAppParameter(rs));
                }
            } catch (SQLException e) {
                throw ExceptionCommonBase.throwExceptionCommonBase(e);
            } finally {
                this.close(rs);
                this.releaseConnection(conn);
            }
        }
        return resultList;
    }

    public String getSysParameter(SysParameterType type) throws ExceptionCommonBase {
        String sql = "select value FROM t_parameter_sys where name = " + SqlUtils.QuataStr(type.toString());
        return this.getString(sql);
    }

    public void setSysParameter(SysParameterType type, String value) throws ExceptionCommonBase {
        String sql = "insert into t_parameter_sys(name, value) values(" + SqlUtils.QuataStr(type.toString()) + "," + SqlUtils.QuataStr(value) + ") on duplicate key update value="
                + SqlUtils.QuataStr(value);
        this.executeUpdate(sql);
    }

    private AppParameter formatAppParameter(ResultSet rs) throws ExceptionCommonBase {
        try {
            AppParameter item = new AppParameter();
            // "id,parent_id,type,name,param,sort,enable,depth,remark,pic_id,begin_time,end_time,update_time,operator_id,isFilter";
            int i = 1;
            item.setId(rs.getInt(i++));
            item.setParentId(rs.getInt(i++));
            int type = rs.getInt(i++);
            item.setType(AppParameterType.lookup(type));
            item.setName(rs.getString(i++));

            String str = rs.getString(i++);
            if (!Utils.stringIsNullOrEmpty(str)) {
                String[] kvs = str.split(",");
                if (kvs != null) {
                    for (String kv : kvs) {
                        String[] k_v = kv.split("=");
                        if (k_v != null && k_v.length == 2) {
                            AppParameterParamType k = AppParameterParamType.lookup(k_v[0]);
                            if (k != AppParameterParamType.none)
                                item.getParam().put(k, k_v[1]);
                        }
                    }
                }
            }

            item.setSort(rs.getInt(i++));
            // pic_id,begin_time,end_time,update_time,operator_id";
            item.setEnable(rs.getBoolean(i++));
            item.setDepth(rs.getInt(i++));
            item.setRemark(rs.getString(i++));
            item.setPicId(rs.getLong(i++));
            item.setBeginTime(Utils.toUtilDate(rs.getTimestamp(i++)));

            item.setEndTime(Utils.toUtilDate(rs.getTimestamp(i++)));
            item.setUpdateTime(Utils.toUtilDate(rs.getTimestamp(i++)));
            item.setOperatorId(rs.getInt(i++));

            return item;
        } catch (SQLException e) {
            throw ExceptionCommonBase.throwExceptionCommonBase(e);
        }

    }

    public int setAppParameter(AppParameter param) throws ExceptionCommonBase {
        int identity = 0;
        if (param.getId() > 0) {
            int updateStatus = param.getUpdateStatus();
            if (updateStatus > 0) {
                StringBuilder sb = new StringBuilder();
                if ((updateStatus & AppParameter.FieldStatus.depth) > 0) {
                    sb.append(", depth = ").append(param.getDepth());
                }
                if ((updateStatus & AppParameter.FieldStatus.enable) > 0) {
                    int enable = param.Enable() ? 1 : 0;
                    sb.append(", enable = ").append(enable);
                }
                if ((updateStatus & AppParameter.FieldStatus.name) > 0) {
                    sb.append(", name = ").append(SqlUtils.QuataStr(param.getName()));
                }
                if ((updateStatus & AppParameter.FieldStatus.param) > 0) {
                    String param_str = SqlUtils.QuataStr(Utils.toString(',', param.getParam()));
                    sb.append(", param = ").append(param_str);
                }
                if ((updateStatus & AppParameter.FieldStatus.parentId) > 0) {
                    sb.append(", parent_id = ").append(param.getParentId());
                }
                if ((updateStatus & AppParameter.FieldStatus.remark) > 0) {
                    sb.append(", remark = ").append(SqlUtils.QuataStr(param.getRemark()));
                }
                if ((updateStatus & AppParameter.FieldStatus.sort) > 0) {
                    sb.append(", sort = ").append(param.getSort());
                }
                if ((updateStatus & AppParameter.FieldStatus.type) > 0) {
                    sb.append(", type = ").append(param.getType().value());
                }
                if ((updateStatus & AppParameter.FieldStatus.picId) > 0) {
                    sb.append(", pic_id = ").append(param.getPicId());
                }
                if ((updateStatus & AppParameter.FieldStatus.beginTime) > 0) {
                    sb.append(", begin_time = ").append(SqlUtils.QuataStr(Utils.toDateString(param.getBeginTime(), "yyyy-MM-dd HH:mm:ss")));
                }
                if ((updateStatus & AppParameter.FieldStatus.endTime) > 0) {
                    sb.append(", end_time = ").append(SqlUtils.QuataStr(Utils.toDateString(param.getEndTime(), "yyyy-MM-dd HH:mm:ss")));
                }
                sb.append(", update_time = ").append(SqlUtils.QuataStr(Utils.toDateString(new Date(), "yyyy-MM-dd HH:mm:ss")));
                String sql = "update t_parameter_app set " + sb.toString().substring(1) + " where id = " + param.getId();
                System.out.println(sql);
                identity = this.getIdentityId(sql);
            }
        } else {
            // pic_id,begin_time,end_time,update_time,operator_id
            String sql = String.format("INSERT INTO t_parameter_app(parent_id,type,name,param,sort,enable,depth,remark,"
                    + "pic_id,begin_time,end_time,update_time,operator_id)VALUES" + "(%1$d,%2$d,%3$s,%4$s,%5$d," + "%6$d,%7$d,%8$s,%9$d,%10$s,%11$s,%12$s,%13$d)",
                    param.getParentId(), param.getType().value(), SqlUtils.QuataStr(param.getName()), SqlUtils.QuataStr(Utils.toString(',', param.getParam())), param.getSort(),
                    param.Enable() ? 1 : 0, param.getDepth(), SqlUtils.QuataStr(param.getRemark()), param.getPicId(),
                    SqlUtils.QuataStr(Utils.toDateString(param.getBeginTime(), "yyyy-MM-dd HH:mm:ss")),
                    SqlUtils.QuataStr(Utils.toDateString(param.getEndTime(), "yyyy-MM-dd HH:mm:ss")),
                    SqlUtils.QuataStr(Utils.toDateString(param.getUpdateTime(), "yyyy-MM-dd HH:mm:ss")), param.getOperatorId());
            identity = this.getIdentityId(sql);
            System.out.println(sql);
        }
        return identity;
    }

    public List<Integer> listAppParameterIdsByType(AppParameterType type, int depth, int page, int rowsOfPage) throws ExceptionCommonBase {
        String sql = "select id FROM t_parameter_app where type = " + type.value() + " and enable =1  and depth =" + depth + " and enable =1 order by sort asc" + " limit " + page
                * rowsOfPage + "," + rowsOfPage;
        return getListInteger(sql);
    }

    public int getAppParameterIdsByTypeCount(AppParameterType type, int depth) throws ExceptionCommonBase {

        String sql = "select count(id) FROM t_parameter_app where" + " type = " + type.value() + " and depth =" + depth + " and enable =1";
        return getInt(sql);
    }


    public List<AppParameter> listAllAppParameter() throws ExceptionCommonBase {
        List<AppParameter> resultList = new ArrayList<AppParameter>();
        String sql = "select " + STR_SELECt_PARAMETER_APP_INFO + " FROM t_parameter_app";
        Connection conn = null;
        ResultSet rs = null;
        try {
             conn = this.getConnection();
             rs = this.executeQuery(conn, sql);
            while (rs.next()) {
                resultList.add(formatAppParameter(rs));
            }
        } catch (SQLException e) {
            throw ExceptionCommonBase.throwExceptionCommonBase(e);
        } finally {
            this.close(rs);
            this.releaseConnection(conn);
        }
        return resultList;
    }

    public List<Integer> listAllAppParameterParentId() throws ExceptionCommonBase {
        String sql = "SELECT DISTINCT(parent_id) FROM t_parameter_app";
        return this.getListInteger(sql);
    }

    /**
     * 获取所有主键ID
     * 
     * @return
     * @throws ExceptionCommonBase
     */
    public List<Integer> listAppParameterIds() throws ExceptionCommonBase {
        String sql = "select id FROM t_parameter_app";
        return getListInteger(sql);
    }
}
